package com.autologistics.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.autologistics.model.Goods;
import com.autologistics.model.Media;
import com.autologistics.model.Playlist;
import com.autologistics.service.MediaService;
import com.autologistics.util.*;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * @author Clarence
 * 
 */
public class MediaAction extends ActionSupport implements ModelDriven<Media> {

	private MediaService mediaService;

	private Media media = new Media();
	
	private Playlist playlist = new Playlist();

	private List<Media> mediaList;

	private File uploadFile; // 鍖呭惈涓婁紶鏂囦欢鍐呭

	private String uploadFileName; // 涓婁紶鏂囦欢鐨勫悕绉帮紱

	private String uploadContentType; // 涓婁紶鏂囦欢鐨凪IME绫诲瀷锛�
	
	private String name; //文件上传后的新名字
	private String fileName;
	
	private PageBean pageBean;
	//默认是1
	private int page=1;
	

	private String startHoursId;
	
	private String startMinutesId;
	
	private String startSecondsId;
	
	private String endHoursId;
	
	private String endMinutesId;
	
	private String endSecondsId;
	
	private String downloadMediaDirectory;
	
	
	private String msg;
	
	private String allMediaId;
	

	public String getAllMediaId() {
		return allMediaId;
	}

	public void setAllMediaId(String allMediaId) {
		this.allMediaId = allMediaId;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getDownloadMediaDirectory() {
		return downloadMediaDirectory;
	}

	public void setDownloadMediaDirectory(String downloadMediaDirectory) {
		this.downloadMediaDirectory = downloadMediaDirectory;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getStartHoursId() {
		return startHoursId;
	}

	public void setStartHoursId(String startHoursId) {
		this.startHoursId = startHoursId;
	}

	public String getStartMinutesId() {
		return startMinutesId;
	}

	public void setStartMinutesId(String startMinutesId) {
		this.startMinutesId = startMinutesId;
	}

	public String getStartSecondsId() {
		return startSecondsId;
	}

	public void setStartSecondsId(String startSecondsId) {
		this.startSecondsId = startSecondsId;
	}

	
	
	public String getEndHoursId() {
		return endHoursId;
	}

	public void setEndHoursId(String endHoursId) {
		this.endHoursId = endHoursId;
	}

	public String getEndMinutesId() {
		return endMinutesId;
	}

	public void setEndMinutesId(String endMinutesId) {
		this.endMinutesId = endMinutesId;
	}

	public String getEndSecondsId() {
		return endSecondsId;
	}

	public void setEndSecondsId(String endSecondsId) {
		this.endSecondsId = endSecondsId;
	}

	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public MediaService getMediaService() {
		return mediaService;
	}

	public void setMediaService(MediaService mediaService) {
		this.mediaService = mediaService;
	}

	public Media getMedia() {
		return media;
	}

	public void setMedia(Media media) {
		this.media = media;
	}
	
	public Playlist getPlaylist() {
		return playlist;
	}

	public void setPlaylist(Playlist playlist) {
		this.playlist = playlist;
	}

	public List<Media> getMediaList() {
		return mediaList;
	}

	public void setMediaList(List<Media> mediaList) {
		this.mediaList = mediaList;
	}

	

	public File getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile(File uploadFile) {
		this.uploadFile = uploadFile;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	@Override
	public Media getModel() {
		// TODO Auto-generated method stub
		return media;
	}

	public String listAllMedia() {

		mediaList = mediaService.listMedia();
		return SUCCESS;
	}

	public String preAddMedia() {
			return SUCCESS;
	}
	
	//媒体管理分页功能
    public String page() throws Exception{  
    	System.out.println("media action：page（）");
		System.out.println("page:"+page);
	    this.pageBean = (PageBean) mediaService.queryForOnePage(GobalValue.pageSize, page);
	    //获取封装了分页信息和数据的pageBean  
	    this.mediaList = this.pageBean.getMediaList(); //获取数据
	    return SUCCESS;  
    }
    
    public String preCheckMediaInfo() {
    	int mediaId=media.getId();
    	media=mediaService.getMediaById(mediaId);
    	
    	
    	
    	return SUCCESS;
    }
    
    public String checkMediaInfo() {
    	return SUCCESS;
    }
    
    public String preUpdateMedia() {
		int mediaId=media.getId();
		media=mediaService.getMediaById(mediaId);
		Time startTime=media.getStartTime();
		String startTimeStr=startTime.toString();
		String startTimeAll[]=startTimeStr.split(":");
//		System.out.println("startTimeAll"+startTimeAll.toString());
		
		//放错设计：比如12:01:03，，为了去除03这个格式
		int tempStartHour=Integer.parseInt(startTimeAll[0]);
		System.out.println("tempStartHour"+tempStartHour);
		int tempStartMinutes=Integer.parseInt(startTimeAll[1]);
		System.out.println("tempStartMinutes"+tempStartMinutes);
		int tempStartSeconds=Integer.parseInt(startTimeAll[2]);
		System.out.println("tempStartMinutes"+tempStartSeconds);
		
		startHoursId=Integer.toString(tempStartHour);
		startMinutesId=Integer.toString(tempStartMinutes);
		startSecondsId=Integer.toString(tempStartSeconds);
		
		Time endTime=media.getEndTime();
		String endTimeStr=endTime.toString();
		String endTimeAll[]=endTimeStr.split(":");
		
		int tempEndHour=Integer.parseInt(endTimeAll[0]);
		System.out.println("tempEndHour"+tempEndHour);
		int tempEndMinutes=Integer.parseInt(endTimeAll[1]);
		System.out.println("tempEndMinutes"+tempEndMinutes);
		int tempEndSeconds=Integer.parseInt(endTimeAll[2]);
		System.out.println("tempEndSeconds"+tempEndSeconds);
		
		endHoursId=Integer.toString(tempEndHour);
		endMinutesId=Integer.toString(tempEndMinutes);
		endSecondsId=Integer.toString(tempEndSeconds);
		
		System.out.println("preUpdateMedia:	mediaId:  "+mediaId);
    	return SUCCESS;
    }
    
    public String updateMedia() throws Exception {
    	//这里做一些输入校验
    	
    	return this.page();
    }
    
    public String deleteMedia() throws Exception {
    	System.out.println("deleteMedia:");
		int mediaId=media.getId();
		System.out.println("deleteMedia:::mediaId"+mediaId);
		//得到媒体文件路径名,并且删除
		media=mediaService.getMediaById(mediaId);
		
//		String deleteFile=media.getPath();
		boolean flagIsDelteFile=this.deleteFile(media.getPath());
		if(flagIsDelteFile){
			System.out.println("成功删除媒体文件。");
		}
		mediaService.deleteMedia(mediaId);
		
    	return this.page();
    }
    public String addMedia(){
    	
    	return SUCCESS;
    }
    
	public String upload() throws Exception{
		
		FileUtil fileUtil = new FileUtil();
//		System.out.println(""+ServletActionContext.getServletContext().getRealPath("/"));
		File file =new File(ServletActionContext.getServletContext().getRealPath("/")+"/DATA");    
		//如果文件夹不存在则创建    
		if  (!file.exists()  && !file.isDirectory())      
		{       
		    System.out.println("//不存在");  
		    file .mkdir();    
		} else   
		{  
		    System.out.println("//目录存在");  
		}
		System.out.println("MediaAction::::::upload........");
		System.out.println("mediaAction+++upload...........");
		String path = ServletActionContext.getServletContext().getRealPath("/DATA");
		System.out.println(ServletActionContext.getServletContext().getRealPath("/"));
		//name 是指文件名 （保存在服务器上的文件名）
		String filename = path+File.separator+media.getFilename()+".mp4";
		//将filename设置为：path
		media.setPath(filename);
		
		try {
			fileUtil.upload(filename, uploadFile);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mediaService.addMedia(media);
		return SUCCESS;  
		}
	public String download() throws IOException{
		media=mediaService.getMediaById(media.getId());
		
		this.downloadMediaDirectory = media.getPath();
	/*	HttpServletResponse response=ServletActionContext.getResponse();*/
		System.out.println("视频文件路径；"+downloadMediaDirectory);
		
		String [] names;
		names = downloadMediaDirectory.split("DATA");
		fileName = names[names.length - 1];	
		
/*		FileInputStream in=null;
		OutputStream out=null;
		if(downloadMediaDirectory!=null){
			try {
				in=new FileInputStream(downloadMediaDirectory);
				out=response.getOutputStream();
				byte[] buf = new byte[GobalValue.DATASIZE];
                int length;
                while ((length = in.read(buf)) != -1) {
                	out.write(buf, 0, length);
                }
                out.flush();				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}*/
		return SUCCESS;
		
	}
/*	public String download(){

		
		
		String [] names;
		names = downloadMediaDirectory.split("DATA");
		fileName = names[names.length - 1];
		return SUCCESS;
	}
	
	public InputStream getDownload() throws Exception{
		return ServletActionContext.getServletContext().getResourceAsStream(downloadMediaDirectory);
	}*/
	
    public String prePlayMedia() {
		int mediaId=media.getId();
		media=mediaService.getMediaById(mediaId);
		//得到startTime和endTime
		if(media.getStartTime()!=null){
			Time startTime=media.getStartTime();
			String startTimeStr=startTime.toString();
			String startTimeAll[]=startTimeStr.split(":");
			
			int tempStartHour=Integer.parseInt(startTimeAll[0]);
			System.out.println("tempStartHour"+tempStartHour);
			int tempStartMinutes=Integer.parseInt(startTimeAll[1]);
			System.out.println("tempStartMinutes"+tempStartMinutes);
			int tempStartSeconds=Integer.parseInt(startTimeAll[2]);
			System.out.println("tempStartMinutes"+tempStartSeconds);
			
			startHoursId=Integer.toString(tempStartHour);
			startMinutesId=Integer.toString(tempStartMinutes);
			startSecondsId=Integer.toString(tempStartSeconds);			
			
		}else{
			//to do nothing
		}
		if(media.getEndTime()!=null){
			Time endTime=media.getEndTime();
			String endTimeStr=endTime.toString();
			String endTimeAll[]=endTimeStr.split(":");
			
			int tempEndHour=Integer.parseInt(endTimeAll[0]);
			System.out.println("tempEndHour"+tempEndHour);
			int tempEndMinutes=Integer.parseInt(endTimeAll[1]);
			System.out.println("tempEndMinutes"+tempEndMinutes);
			int tempEndSeconds=Integer.parseInt(endTimeAll[2]);
			System.out.println("tempEndSeconds"+tempEndSeconds);
			
			endHoursId=Integer.toString(tempEndHour);
			endMinutesId=Integer.toString(tempEndMinutes);
			endSecondsId=Integer.toString(tempEndSeconds);			
		}else{
			//to do nothing
		}

		System.out.println("prePlayMedia:	mediaId:  "+mediaId);
    	return SUCCESS;
    }  
    
    public String playMedia() throws Exception {
    	//这里做一些输入校验
		int mediaId=media.getId();
		media=mediaService.getMediaById(mediaId);
		
    	System.out.println("mediaAction:upload");
		System.out.println(startHoursId);
		System.out.println(startMinutesId);
		System.out.println(startSecondsId);
		int sh=Integer.parseInt(startHoursId);
		int sm=Integer.parseInt(startMinutesId);
		int ss=Integer.parseInt(startSecondsId);
		Time startTime=new Time(sh,sm,ss);
		if(startTime==null){
			System.out.println("startTime 是空值，调用构造器错误");
		}else{
			System.out.println("startTime"+startTime.toString());
		}
		media.setStartTime(startTime);
		int eh=Integer.parseInt(endHoursId);
		int em=Integer.parseInt(endMinutesId);
		int es=Integer.parseInt(endSecondsId);
		//做个校验
		if(sh>eh){
			msg="开始时间应小于结束时间";
			return ERROR;
		}else if(sh==eh){
			if(sm>em){
				msg="开始时间应小于结束时间";
				return ERROR;
			}else if(sm==em){
				if(ss>=es){
					msg="开始时间应小于结束时间";
					return ERROR;
				}
			}
		}
		Time endTime=new Time(eh,em,es);
		
		media.setEndTime(endTime);
		
		//得到时间差
		int length=(int) ((endTime.getTime()-startTime.getTime())/1000);
		int lengthHours=length%(24*3600)/3600;
		int lengthMinutes=length%(3600)/60;
		int lengthSeconds=(length%60)/60;
		Time mediaLength=new Time(lengthHours,lengthMinutes,lengthSeconds);
		System.out.println("line:471 playMedia"+mediaLength.toString());
		
		media.setLength(mediaLength);
		
		
		mediaService.updateMedia(media);
    	
    	return this.page();
    }
    
    /**
     *得到所有的视频列表 
     * @return
     */
    public String prePlayMediaTogether() {
    	
    	mediaList = mediaService.listMedia();
    	
    	
    	return SUCCESS;
    }
    
    /**
     * 此方法是播放所有的媒体
     * @return
     * @throws Exception
     */
    public String playMediaTogether() throws Exception {
    	
    	System.out.println("进入了 ：  playmediaTogether方法中");
		int sh=Integer.parseInt(startHoursId);
		int sm=Integer.parseInt(startMinutesId);
		int ss=Integer.parseInt(startSecondsId);
		Time startTime=new Time(sh,sm,ss);
/*		if(startTime==null){
			System.out.println("startTime 是空值，调用构造器错误");
		}else{
			System.out.println("startTime"+startTime.toString());
		}*/
		playlist.setStartTime(startTime);
		
		int eh=Integer.parseInt(endHoursId);
		int em=Integer.parseInt(endMinutesId);
		int es=Integer.parseInt(endSecondsId);
		//做个开始时间和结束时间的校验
		if(sh>eh){
			msg="开始时间应小于结束时间";
			return ERROR;
		}else if(sh==eh){
			if(sm>em){
				msg="开始时间应小于结束时间";
				return ERROR;
			}else if(sm==em){
				if(ss>=es){
					msg="开始时间应小于结束时间";
					return ERROR;
				}
			}
		}
		Time endTime=new Time(eh,em,es);
		
		playlist.setEndTime(endTime);

		System.out.println("allMediaId:  "+allMediaId);


		String[] allMediaIdsArray = allMediaId.split("@@");
		/*System.out.println("-----开始----");*/
		for(int i=0;i<allMediaIdsArray.length;i++){
			System.out.println(allMediaIdsArray[i]);		
		}
		
		/*System.out.println("-----结束----");*/
		String fileString="";
		
		//根据传过来的mediaIds,然后得到每个mediaId的存储在服务器上的路径;并且以@@作为分隔符
		for (int j = 0; j < allMediaIdsArray.length; j++) {
			fileString=fileString+mediaService.getMediaById(Integer.parseInt(allMediaIdsArray[j])).getPath()+"@@";
		}
		System.out.println("fileString: "+fileString);
		playlist.setFile(fileString);
		
		System.out.println("playlist	");
		System.out.println("title	:"+playlist.getTitle());
		System.out.println("startTime	:"+playlist.getStartTime());
		System.out.println("endTime	:"+playlist.getEndTime());
		System.out.println("fileString: "+playlist.getFile());
		
		mediaService.addPlayList(playlist);
		return SUCCESS;	
    }
    
    
	public String searchMedia() {
		//暂时将userId定死，做测试 
//		int userId=goods.getUser().getId();
//		int tempuserId=1;
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session=request.getSession();
		if(GobalValue.FAIL.equals(hasSession(session))){
			return GobalValue.FAIL;
		}
		int userid=(int) session.getAttribute("id");
		
		String filename=media.getFilename();
//		goodsList=goodsService.listAll(tempuserId);
		mediaList=mediaService.searchMedia(filename);
		//to get list of goodskind.
//		System.out.println("to invoke goodskindService");
//		goodsKindList=goodskindService.listAll();
		
		return SUCCESS;
	}

    /**
     * 判断是否有session
     * @param session
     * @return
     */
    public String hasSession(HttpSession session){
    	if(session==null){
    		return GobalValue.FAIL;
    	}else{
    		return SUCCESS;
    	}
    }
    
    //以下是validation做校验
/*    public void validateAddMedia(){
    	if(media.getFilename()==null){
 //   		addFieldError(,);
    		
    	}
    	
    	return SUCCESS;
    }
    */
    /**根据路径删除指定的目录或文件，无论存在与否 
     * 
     * @param sPath 要删除的目录或文件
     * @return  删除成功返回 true，否则返回 false。 
     */
    public boolean deleteFile(String sPath) {  
        boolean flag = false;  
        File file = new File(sPath);  
        // 路径为文件且不为空则进行删除  
        if (file.isFile() && file.exists()) {  
            file.delete();  
            flag = true;  
        }  
        return flag;  
    }
}
